import React, { useEffect, useState } from 'react';
import './App.css';
import MachineRoom from './components/MachineRoom';
// 机房对象
let room: MachineRoom;
let canvas: HTMLCanvasElement;
interface setMsg {
  planePos: {
    left: number,
    top: number
  },
  // 信息面板的可见性
  planeDisplay: string
  // 当前机柜信息的详细信息
  curCabinet: {
    // 名称
    name: string,
    // 温度
    temperature: number,
    // 容量
    capacity: number,
    // 服务器数量
    count: number

  }
}
function App() {

  // 建立canvas画布，并且通过ref 获取其HTMLCanvasElement对象
  const [msg, setMsg] = useState<setMsg>({
    // 信息面板的位置
    planePos: {
      left: 0,
      top: 0
    },
    // 信息面板的可见性
    planeDisplay: "noon",
    // 当前机柜信息的详细信息
    curCabinet: {
      // 名称
      name: 'Loading......',
      // 温度
      temperature: 0,
      // 容量
      capacity: 0,
      // 服务器数量
      count: 0

    }
  })
  useEffect(() => {
    if (!canvas) { return }
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    room = new MachineRoom(canvas);
    room.loadGLTF('machineRoom.gltf')
    room.animate()
    // 定义鼠标划入机柜，显示信息面板
    room.onMouseMoveCabinet = () => {
      setMsg({
        planeDisplay: "block", curCabinet: {// 名称
          name: '',
          // 温度
          temperature: 0,
          // 容量
          capacity: 0,
          // 服务器数量
          count: 0
        }, planePos: {
          left: 0,
          top: 0
        }
      })
    }
    //当鼠标在机柜上移动，让信息面板随鼠标移动
    room.onMouseMoveCabinet = (left, top) => {
      setMsg({
        planeDisplay: "block", curCabinet: {// 名称
          name: '',
          // 温度
          temperature: 0,
          // 容量
          capacity: 0,
          // 服务器数量
          count: 0
        }, planePos: {
          left: top,
          top: left
        }
      })
    };
    //当鼠标划出机柜，隐藏信息面板
    room.onMouseOutCabinet = () => {
      setMsg({
        planeDisplay: "noon", curCabinet: {// 名称
          name: '',
          // 温度
          temperature: 0,
          // 容量
          capacity: 0,
          // 服务器数量
          count: 0
        }, planePos: {
          left: 0,
          top: 0
        }
      })
    };
  })
  // 鼠标移动事件
  const MouseMove = (e: any) => {
    let clientX: number = e.clientX
    let clientY: number = e.clientY
    room.selectCabinet(clientX, clientY)
  }
  // const {planePos:{left,top}, planeDisplay:display,curCabinet:{name,temperature,capacity,count}} = msg
  return (
    <div className="App" onMouseMove={MouseMove}>
      <canvas id='canvas' ref={(ele: HTMLCanvasElement) => (canvas = ele)}></canvas>
      <div id='plane' style={{ left: msg.planePos.left, top: msg.planePos.top, display: msg.planeDisplay }}>
        <p>机柜名称：{msg.curCabinet.name}</p>
        <p>机柜的温度：{msg.curCabinet.temperature}度</p>
        <p>机柜的使用情况：{msg.curCabinet.count / msg.curCabinet.capacity}</p>
      </div>
    </div>
  );
}

export default App;
